<template>
  <van-pull-refresh v-model="refreshing" @refresh="getData(true)">
    <van-list
      v-model:loading="loading"
      v-model:error="listErr"
      :finished="finished"
      finished-text="没有更多了"
      error-text="请求失败，点击重新加载"
      @load="getData"
    >
      <van-swipe-cell
        v-for="video in list"
        :key="video.id"
        @click="($event) => cellClick($event, video.id)"
      >
        <VideoItem
          :title="video.title"
          :thumbnail="video.thumbnail"
          :is-live="isLive"
          :start-time="video.startTime || ''"
        >
          <template #subtitle>
            {{
              isLive
                ? `直播号：${video.meetingRoomNumber}`
                : `${video.speaker ? `主讲人：${video.speaker}` : ""}`
            }}
          </template>
          <template #default>
            <span class="live-time" v-if="isLive">{{ video.startTime }}</span>
            <!--观看数-->
            <!-- <span class="video-total">{{ video.viewtotal }}</span> -->
            <div class="live-space"></div>
            <div
              class="right-item"
              v-if="name === 'live_my'"
              @click.stop="share(video)"
            >
              <i class="sdlive icon-share-s"></i>
            </div>
            <template v-if="isShowLike">
              <div class="right-item">
                <i class="sdlive icon-dianzan_kuai"></i>
                <span class="number">{{
                  video.thumbsUpNum >= 100 ? "99+" : video.thumbsUpNum
                }}</span>
              </div>
              <div class="right-item">
                <i class="sdlive icon-sc-active"></i>
                <span class="number">{{
                  video.collectNum >= 100 ? "99+" : video.collectNum
                }}</span>
              </div>
            </template>
          </template>
        </VideoItem>
        <template #right v-if="isShowDel">
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            @click="delItem(video.id)"
          />
        </template>
      </van-swipe-cell>
    </van-list>
  </van-pull-refresh>
</template>

<script setup>
import { computed, ref, defineExpose } from 'vue'
import { useRouter } from 'vue-router'

import VideoItem from './video-item.vue'

import { WEB_HREF } from '@/utils/index'
import { wxShare } from '@/utils/wx'
import { insertShareLog } from '@/api/share'

import { useListCommon } from '@/hooks/useList'

const $router = useRouter()

const props = defineProps({
  name: {
    type: String,
    default: 'live_my'
  },
  isLive: {
    type: Boolean,
    default: true
  },
  searchContext: {
    type: String,
    default: ''
  }
})

const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const listErr = ref(false)

const isInit = ref(false)

// 最大分页数20
const pageLimit = 20

const isShowDel = computed(() =>
  ['live_my', 'live_collect', 'video_collect'].includes(props.name)
)

const isShowLike = computed(() =>
  ['live_all', 'live_collect', 'video_all', 'video_collect'].includes(
    props.name
  )
)

const { page, total, list, getListData, delListItem } = useListCommon()

const getData = async(isReset = false) => {
  // 初始加载
  if (!isInit.value) {
    isInit.value = true
    // if (isReset) {
    //   return
    // }
    return
  }
  // if (props.name === 'video_collect') {
  //   console.log('get data')
  // }
  try {
    // 刷新
    if (isReset) {
      list.value = []
      page.value = 1
      total.value = 1
      // 重置状态
      loading.value = true
      finished.value = false
      refreshing.value = false
      listErr.value = false
    }
    // 到了最大分页数，不在加载
    if (page.value > pageLimit) {
      finished.value = true
      return
    }
    // 如果加载完成不在加载
    if (list.value.length >= total.value) {
      return
    }
    const data = await getListData(
      props.isLive,
      props.name,
      props.searchContext
    )
    page.value = page.value + 1
    list.value = list.value.concat(data)
    loading.value = false
    if (list.value.length >= total.value) {
      finished.value = true
    }
  } catch (error) {
    loading.value = false
    listErr.value = true
  }
}

const cellClick = (position, id) => {
  if (position === 'cell') {
    goToInfo(id)
  } else if (position === 'right') {
    // TODO: del 直播或者取消收藏
  }
}

// 去详情页
const goToInfo = (id) => {
  if (props.isLive) {
    $router.push({
      path: '/info',
      query: {
        id
      }
    })
  } else {
    $router.push({
      path: '/video-detail',
      query: {
        id
      }
    })
  }
}

const delItem = async(id) => {
  delListItem(id, props.name, () => {
    getData(true)
  })
}

// 分享
const share = (video) => {
  wxShare(
    {
      title: video.title,
      desc: video.briefIntroduction,
      link: `${WEB_HREF}/info?id=${video.id}`
    },
    true,
    (res) => {
      console.log('分享成功 >>>', res)
      insertShareLog(video.id)
    }
  )
}

// watch(
//   () => props.searchContext,
//   (val) => {
//     getData(true)
//   }
// )

defineExpose({
  getData
})
</script>

<style lang="less" scoped>
.live-space {
  flex: 1;
}
.live-time {
  font-size: 12px;
  color: #ffd083;
  padding: 3px 5px;
  border: 1px solid #ffd083;
  border-radius: 4px;
}
.right-item {
  max-width: 55px;
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  color: #999;
  overflow: hidden;
  margin-left: 5px;
  // .icon-dianzan_kuai {
  //   color: #b62242;
  // }
  // .icon-sc-active {
  //   color: #eda319;
  // }
  .icon-share-s {
    color: var(--vb-primary-color);
    padding: 5px;
  }
  .number {
    font-size: 12px;
    padding-left: 5px;
  }
}
.delete-button {
  height: 100%;
}

.video-total {
  font-size: 12px;
  color: #999;
  padding: 3px 5px;
}

.last-padding {
  height: 25px;
}
</style>
